//
//  Regex.swift
//  App_Common_FoundationExtensions
//
//  Created by liulihui on 2021/7/29.
//

import Foundation

public struct Regex: Equatable {
    let regularExpression: NSRegularExpression?

    public init(_ pattern: String, options _: NSRegularExpression.Options = []) {
        do {
            regularExpression = try NSRegularExpression(pattern: pattern, options: [])
        } catch _ {
            regularExpression = nil
        }
    }

    public func matchs(_ string: String) -> Bool {
        guard let regex = regularExpression else { return false }
        let result = regex.rangeOfFirstMatch(in: string, options: [], range: NSRange(string.startIndex..., in: string))
        return !NSEqualRanges(result, NSRange(location: NSNotFound, length: 0))
    }

    public static func ~= (pattern: Regex, value: String) -> Bool {
        pattern.matchs(value)
    }
}
